package com.ly.other.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ly.bean.Result;
import com.ly.damai.entity.Product;
import com.ly.other.biz.IProductService;
import com.ly.other.vo.DacuOrder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("dacu")
public class DaCuDo {

    @Autowired
    IProductService productService;
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private TaskScheduler taskScheduler;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    Date begin;
    Date end;

    @Transactional
    @RequestMapping("ready")
    public Result ready(){
        LambdaQueryWrapper<Product> lqw = new LambdaQueryWrapper<>();
        lqw.ge(Product::getNums, 8000);
        List<Product> products = productService.list(lqw);
        ValueOperations forValue = redisTemplate.opsForValue();
        // 设置促销商品数量
        products.forEach(product -> {
            // 扣库存
            product.setNums(product.getNums() - 1000);
            // 保存到 MySQL
            productService.updateById(product);
            // 设置促销数量
            product.setNums(1000);
            // 保存商品数量, 方便扣减库存数
            forValue.set("dacu_nums_" + product.getPid(), product.getNums());
        });
        // 将促销商品保存至 redis 中
        redisTemplate.opsForValue().set("dacu-products", products);

        // 设置开始时间和结束时间
        begin = new Date(System.currentTimeMillis() + 1000 * 10);  // 十秒后开始
        end = new Date(System.currentTimeMillis() + 1000 * 60 * 5);     //  30秒后结束

        taskScheduler.schedule( ()->finish(), end );

        // 启动结束任务
        return new Result(1,"大促准备完成!",null);
    }

    @RequestMapping("products")
    public Object getProducts(){
        if(begin == null || System.currentTimeMillis() < begin.getTime()){
            return null;
        }
        return redisTemplate.opsForValue().get("dacu-products");
    }

    // uid 应该从 jwt 解析出来 => jwt 有可能超时
    @RequestMapping("commit")
    public Result commit(int pid, int nums, int uid){
        if(begin == null || System.currentTimeMillis() < begin.getTime()){
            return new Result(-2, "促销活动还未开始", null);
        }
        //  扣减库存
        String key = "dacu_nums_" + pid;
        ValueOperations forValue = redisTemplate.opsForValue();
        Integer redisNums = (Integer) forValue.get(key);
        if (redisTemplate.hasKey(key) == false) {
            return new Result(-3, "非大促商品", null);
        }
        if(redisNums < nums){
            return new Result(-1, "商品数量不足", null);
        }
        forValue.set(key, redisNums - nums);
        // decrement or increment 直接对 key 对应的值 增减数量, 要求 value 必须是数值
        // forValue.decrement(key, nums);
        // TODO 发送消息到 rabbitmq
        DacuOrder order = new DacuOrder(pid,uid,nums);
        rabbitTemplate.convertAndSend("dacu.queue", order);

        return new Result(1, "订单已受理!", null);
    }

    @Transactional
    public void finish(){
        // 将时间清空
        begin = end = null;
        // 将未销售完的商品提交会MySQL
        ValueOperations forValue = redisTemplate.opsForValue();

        Set keys = redisTemplate.keys("dacu_nums_*");
        keys.forEach(key->{
            Integer nums = (Integer) forValue.get(key);
            String pid = key.toString().substring("dacu_nums_".length());
            Product product = productService.getById(pid);
            product.setNums(product.getNums() + nums);
            productService.updateById(product);
        });
        // 清空redis数据
        redisTemplate.delete(keys);
        redisTemplate.delete("dacu-products");

        System.out.println("促销活动结束!");
    }
}
